package com.yuntoyun.codeavatar.app.activity.home;

import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.yuntoyun.codeavatar.app.R;
import com.yuntoyun.codeavatar.app.fwcore.core.AppCoreSign;
import com.yuntoyun.fwcore.adapter.FwListAdapter;
import com.yuntoyun.fwcore.appext.data.AppData;
import com.yuntoyun.fwcore.base.FwBaseActivity;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.plug.tool.FwNavigationTool;
import com.yuntoyun.fwcore.view.FwGridView;
import com.yuntoyun.fwcore.view.FwLetterSlideBarView;
import com.yuntoyun.fwcore.view.bean.FwCityBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import io.reactivex.Observable;

public class SwitchCityActivity extends FwBaseActivity implements FwLetterSlideBarView.OnTouchingLetterChangedListener, AbsListView.OnScrollListener, AdapterView.OnItemClickListener {

    private final int gActionLoad = 901;

    @BindView(R.id.lvw_city_list)
    ListView lvw_city_list;
    @BindView(R.id.fwLsb_letter_bar)
    FwLetterSlideBarView fwLsb_letter_bar;

    //滚动标识
    private boolean isScroll;

    //缓存全部城市
    private List<FwCityBean> allCities = new ArrayList<>();
    //ListView首部布局
    private View gListHeadView;
    private TextView tvw_current_location;
    private FwGridView fwGvw_history_list;
    private FwListAdapter fwHistoryListAdapter = null;
    private List<Map<String, FwCityBean>> gHistoryList = new ArrayList<>();
    //筛选城市
    private Map<String, Integer> gSearchLetterRecord = new HashMap<>();
    private List<Map<String, FwCityBean>> gSearchList = new ArrayList<>();
    private FwListAdapter gSearchAdapter = null;

    @Override
    protected void beforeLayout() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_home_switch_city;
    }

    @Override
    protected void initView() {
        this.initHeadView();
        //搜索初始化
        this.gSearchList = new ArrayList<>();
        this.gSearchAdapter = new FwListAdapter(this, gSearchList, R.layout.activity_home_switch_city_list_option, gSearchListViewHolder);
        this.lvw_city_list.setAdapter(gSearchAdapter);
        this.lvw_city_list.setOnItemClickListener(this);
        //侧边栏
        this.fwLsb_letter_bar.setOnTouchingLetterChangedListener(this);
    }

    @Override
    protected void initData() {
        this.setCityInfo();
        this.doLoadData();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initNavigation() {
        FwNavigationTool.setHeadBar(this, "切换城市");
    }

    @Override
    protected void messageHandler(Message msg) {

    }

    @Override
    protected void messageHandler(FwResultJsonDataModel model) {
        switch (model.getIndex()) {
            case gActionLoad:
                this.setLoadData(model.getFwData());
                break;
        }
    }

    @Override
    protected void messageHandler(FwResultJsonListDataModel model) {

    }

    @Override
    public void onClick(View v) {
        if (null == v) return;

        switch (v.getId()) {
            case R.id.tvw_current_location:
                finish();
                break;
        }
    }

    /////////
    ///扩展事件
    /////////

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_TOUCH_SCROLL || scrollState == SCROLL_STATE_FLING) {
            isScroll = true;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position > 0) {
            int realIndex = position - lvw_city_list.getHeaderViewsCount();
            //目标数据源
            FwCityBean bean = allCities.get(realIndex);
            AppData.setCityId(bean.getCityCode());
            AppData.setCityName(bean.getName());
            //最多12个历史记录
            AppData.cacheHistoryCity(bean.getName(), bean.getCityCode(), 6);
            //返回上页
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    public void onTouchingLetterChanged(String s) {
        isScroll = false;
        if (gSearchLetterRecord.containsKey(s.toUpperCase())) {
            int position = gSearchLetterRecord.get(s.toUpperCase());
            lvw_city_list.setSelection(position);
        } else if (s.toUpperCase() == "#") {
            lvw_city_list.setSelection(0);
        }
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    private FwListAdapter.IFwListViewHolder gSearchListViewHolder = new FwListAdapter.IFwListViewHolder() {
        @Override
        public View getView(int position, List<? extends Map<String, ?>> data, View layoutView) {
            FwCityBean tmpCity = (FwCityBean) data.get(position).get("item");
            TextView tvw_letter = layoutView.findViewById(R.id.tvw_letter);
            TextView tvw_city_name = layoutView.findViewById(R.id.tvw_city_name);
            tvw_city_name.setText(tmpCity.getName());
            tvw_city_name.setTag(tmpCity.getCityCode());
            tvw_letter.setText(tmpCity.getPinyin());
            tvw_letter.setVisibility((tmpCity.isShowLetter()) ? View.VISIBLE : View.GONE);
            return layoutView;
        }
    };

    private void initHeadView() {
        //顶部布局
        gListHeadView = fwLayoutInflater.inflate(R.layout.activity_home_switch_city_header, null);
        if (lvw_city_list.getHeaderViewsCount() > 0) {
            lvw_city_list.removeAllViews();
            lvw_city_list.addHeaderView(gListHeadView);
        } else {
            lvw_city_list.addHeaderView(gListHeadView);
        }
        tvw_current_location = gListHeadView.findViewById(R.id.tvw_current_location);
        tvw_current_location.setOnClickListener(this);
        //历史记录
        fwGvw_history_list = gListHeadView.findViewById(R.id.fwGvw_history_list);
        //加载历史数据
        gHistoryList.clear();
        List<JsonObject> pCityList = AppData.cacheHistoryCity();
        if (null != pCityList && pCityList.size() > 0) {
            for (JsonObject joItem : pCityList) {
                Map<String, FwCityBean> tmpMap = new HashMap<>();
                FwCityBean tmpCity = new FwCityBean(fwGsonUtil.getString(joItem, "cityName"), fwGsonUtil.getString(joItem, "cityCode"));
                tmpMap.put("item", tmpCity);
                this.gHistoryList.add(tmpMap);
            }
        }

        this.fwHistoryListAdapter = new FwListAdapter(this, gHistoryList, R.layout.activity_home_switch_city_header_history_option,
                new FwListAdapter.IFwListViewHolder() {
                    @Override
                    public View getView(int position, List<? extends Map<String, ?>> data, View layoutView) {
                        FwCityBean tmpCity = (FwCityBean) data.get(position).get("item");
                        TextView tvw_option = layoutView.findViewById(R.id.tvw_option);
                        tvw_option.setText(tmpCity.getName());
                        tvw_option.setTag(tmpCity.getCityCode());
                        return layoutView;
                    }
                });
        this.fwGvw_history_list.setAdapter(fwHistoryListAdapter);
        this.fwGvw_history_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //目标数据源
                FwCityBean bean = gHistoryList.get(position).get("item");
                AppData.setCityId(bean.getCityCode());
                AppData.setCityName(bean.getName());
                //返回上页
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    private void setLoadData(JsonObject joData) {
        if (null == joData) return;

        allCities.clear();

        //当前城市
        if (null == tvw_current_location.getTag()) {
            JsonObject joLocationCity = fwGsonUtil.getJsonObject(joData, "locationCity");
            tvw_current_location.setText(fwGsonUtil.getString(joLocationCity, "cityName"));
            tvw_current_location.setTag(fwGsonUtil.getString(joLocationCity, "cityCode"));
        }

        //设置全国城市数据
        JsonObject groupJarr = fwGsonUtil.getJsonObject(joData, "groupCities");
        Set<Map.Entry<String, JsonElement>> entrySet = groupJarr.entrySet();
        ArrayList<FwCityBean> list = new ArrayList<>();
        for (Map.Entry<String, JsonElement> stringEntry : entrySet) {
            String key = stringEntry.getKey();
            JsonArray citydata = (JsonArray) stringEntry.getValue();
            for (int i = 0; i < citydata.size(); i++) {
                JsonObject jb = fwGsonUtil.getJsonObject(citydata, i);
                list.add(new FwCityBean(fwGsonUtil.getString(jb, "name"), fwGsonUtil.getString(jb, "code"), fwGsonUtil.getString(jb, "first_word")));
            }
        }
//        //当前定位城市(#)
//        FwCityBean topCityBean = new FwCityBean("定位", "0", "");
//        allCities.add(topCityBean);
        //动态数据
        allCities.addAll(list);

        //筛选城市
        this.doSearch();
    }

    private void doLoadData() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("fwUserLongitude", "");
        map.put("fwUserLatitude", "");
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getSwitchCity(map);
        super.doPostData(this.gActionLoad, observable, true);
    }

    //筛选城市
    private void doSearch() {
        String keywords = "";
        //重新记录
        this.gSearchLetterRecord.clear();
        this.gSearchList.clear();

        for (FwCityBean bean : this.allCities) {
            if (-1 != bean.getName().indexOf(keywords)) {
                Map<String, FwCityBean> tmpMap = new HashMap<>();
                FwCityBean tmpCity = new FwCityBean(bean.getName(), bean.getCityCode(), bean.getPinyin().toUpperCase(), false);
                tmpMap.put("item", tmpCity);
                if (!gSearchLetterRecord.containsKey(tmpCity.getPinyin().toUpperCase())) {
                    gSearchLetterRecord.put(tmpCity.getPinyin(), -1);
                    tmpCity.setShowLetter(true);
                }
                this.gSearchList.add(tmpMap);
            }
        }
        //设置定位索引
        FwCityBean tmpItemCity = null;
        for (int i = 0; i < this.gSearchList.size(); i++) {
            tmpItemCity = this.gSearchList.get(i).get("item");
            if (tmpItemCity.isShowLetter()) {
                this.gSearchLetterRecord.put(tmpItemCity.getPinyin().toUpperCase(), i);
            }
        }
        //更新数据
        gSearchAdapter.notifyDataSetChanged();
    }

    private void setCityInfo() {
        String pCityId = AppData.getCityId();
        String pCityName = AppData.getCityName();
        if ((!TextUtils.isEmpty(pCityId)) && (!TextUtils.isEmpty(pCityName))) {
            tvw_current_location.setText(pCityName);
            tvw_current_location.setTag(pCityId);
        }
    }
}
